<template>
  <CommonPage>
    <template #action>
      <n-button v-permission="'AddGoods111'" type="primary" @click="handleAdd()">
        <i class="i-material-symbols:add mr-4 text-18" />
        创建商品
      </n-button>
    </template>

    <MeCrud
      ref="$table"
      v-model:query-items="queryItems"
      :scroll-x="1200"
      :columns="columnFields"
      :get-data="api.read"
    >
      <MeQueryItem label="商品名" :label-width="50">
        <n-input v-model:value="queryItems.name" type="text" placeholder="请输入商品名" clearable />
      </MeQueryItem>
      <!-- <MeQueryItem label="竞拍人" :label-width="60">
        <n-input v-model:value="queryItems.auctionUserName" type="text" placeholder="请输入竞拍人" clearable />
      </MeQueryItem> -->
    </MeCrud>

    <MeModal ref="modalRef" width="1020px">
      <n-form
        ref="modalFormRef"
        label-placement="left"
        label-align="right"
        :model="modalForm"
        :disabled="['view', 'viewGoods'].includes(modalAction)"
      >
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi
            v-for="field in formFields"
            :key="field.key"
            :span="field.span || 12"
            :label="field.title"
            :disabled="modalAction !== 'add'"
            label-width="130px"
          >
            <n-select
              v-if="field.options?.length > 0"
              v-model:value="modalForm[field.key]"
              :options="field.options"
              label-field="name"
              value-field="id"
              clearable
              filterable
            />
            <n-upload
              v-else-if="field.isImage"
              :action="`/api/upload`"
              list-type="image-card"
              :default-file-list="
                ['setGoods', 'viewGoods'].includes(modalAction) && [
                  {
                    id: modalForm[field.key],
                    name: modalForm[field.key],
                    url: modalForm[field.key],
                    status: 'finished',
                  },
                ]
              "
              :max="1"
              :multiple="false"
              @finish="(e) => onFinish(e, field.key)"
            >
              点击上传
            </n-upload>
            <n-switch v-else-if="field.type === 'bool'" v-model:value="modalForm[field.key]" />
            <n-date-picker
              v-else-if="['datetime', 'date', 'time'].includes(field.type)"
              v-model:value="modalForm[field.key]"
              :type="field.type"
              :value-format="
                field.type === 'datetime'
                  ? 'yyyy-MM-dd HH:mm:ss'
                  : field.type === 'date'
                  ? 'yyyy-MM-dd'
                  : 'HH:mm:ss'
              "
              clearable
            />
            <n-divider v-else-if="field.isFirst">{{ field.spanText }}</n-divider>
            <n-input v-else :type="field.isInputArea ? 'textarea' : ''" v-model:value="modalForm[field.key]" />
          </n-form-item-gi>
        </n-grid>
      </n-form>
    </MeModal>
  </CommonPage>
</template>

<script setup>
import { NButton } from 'naive-ui'
import { MeCrud, MeQueryItem, MeModal } from '@/components'
import { useCrud } from '@/composables'
import api, { genColumns, statusOptions } from './api'
import dayjs from 'dayjs'

defineOptions({ name: 'UserMgt' })

const $table = ref(null)
/** QueryBar筛选参数（可选） */
const queryItems = ref({})

onMounted(() => {
  $table.value?.handleSearch()
})

const tempColumns = genColumns({})
const initForm = tempColumns
  .filter((i) => i.isForm)
  .reduce((pre, cur) => {
    pre[cur.key] = cur.options
      ? undefined
      : ['datetime', 'date', 'time'].includes(cur.type)
      ? dayjs().valueOf()
      : ''
    return pre
  }, {})

const {
  modalRef,
  modalFormRef,
  modalForm,
  modalAction,
  handleAdd,
  handleDelete,
  handleOpen,
  handleSave,
} = useCrud({
  name: '商品',
  initForm,
  doCreate: api.create,
  doDelete: api.delete,
  doUpdate: api.update,
  refresh: () => $table.value?.handleSearch(),
})

function onFinish({ event }, key) {
  const result = JSON.parse(event.target.response)
  modalForm.value[key] = result.data.imgUrl
}

// async function handleEnable(row) {
//   row.enableLoading = true
//   try {
//     await api.update({ id: row.id, enable: !row.enable })
//     row.enableLoading = false
//     $message.success('操作成功')
//     $table.value?.handleSearch()
//   } catch (error) {
//     row.enableLoading = false
//   }
// }

function handleOpenRolesSet(row) {
  handleOpen({
    action: 'setRole',
    title: '设置审核状态',
    row,
    onOk: onSave,
  })
}

function onSave() {
  if (modalAction.value === 'setRole') {
    return handleSave({
      api: () => api.update(modalForm.value),
      cb: () => $message.success('设置成功'),
    })
  } else if (['setGoods', 'viewGoods'].includes(modalAction.value)) {
    return handleSave({
      api: () => api.update(modalForm.value),
      cb: () => $message.success('商品修改成功'),
    })
  }
  handleSave()
}

const columns = genColumns({ handleOpenRolesSet, handleOpen, handleDelete, onSave, h })

const columnFields = computed(() => columns.filter((col) => col.isTable))
const formFields = computed(() =>
  columns.filter((col) =>
    modalAction.value === 'setRole'
      ? col.isSetRole
      : modalAction.value === 'reset'
      ? col.isResetPwd
      : col.isForm
  )
)
</script>
